<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="12">
          <SearchBar
            :queryInfo="queryInfo"
            @searchByName="searchUniversity"
            @clearInput="clearInput"
            @searchByArea="searchSchoolByArea"
          ></SearchBar>
        </el-col>
        <!-- 添加高校模块 -->
        <el-col :span="12">
          <div class="right">
            <el-button type="success" plain @click="excelShow">
              导出Excel表格
            </el-button>
            <!-- 批量导入企业 -->
            <el-button type="success" plain @click="excelImport">
              批量导入
            </el-button>
            <el-button type="primary" @click="showAddCom"> 添加高校 </el-button>
          </div>
          <!-- 批量导入数据 -->
          <el-dialog title="导入文件" :visible.sync="excelImportShow">
            <el-upload
              class="upload-demo"
              :limit="1"
              :file-list="fileList"
              :before-upload="beforeUpload"
            >
              <el-button slot="trigger" size="small" type="primary"
                >选取文件</el-button
              >
              <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
              <a
                href="/financial-admin/exportInOutBusiClass-excel"
                rel="external nofollow"
                download="模版"
              >
                <el-button size="small" type="success">下载模板</el-button></a
              >
              <div slot="tip" class="el-upload-list__item-name">
                {{ fileName }}
              </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
              <el-button @click.native="excelImportShow = false"
                >取消</el-button
              >
              <el-button
                type="primary"
                @click.native="submitUpload()"
                :loading="addLoading"
                >提交</el-button
              >
            </div>
          </el-dialog>
          <el-dialog title="添加高校" :visible.sync="dialogVisible" width="50%">
            <el-form
              :label-position="labelPosition"
              label-width="80px"
              :model="universityForm"
            >
              <el-form-item label="高校名称:" prop="schoolName">
                <el-input
                  v-model="universityForm.schoolName"
                  placeholder="请输入高校名"
                ></el-input>
              </el-form-item>
              <el-form-item label="高校代码:" prop="schoolId">
                <el-input
                  v-model="universityForm.schoolId"
                  placeholder="请输入高校代码"
                ></el-input>
              </el-form-item>
              <el-form-item label="地区:" prop="provinceName">
                <el-cascader
                  size="large"
                  :options="options"
                  v-model="selectedOptions"
                  @change="handleChange"
                >
                </el-cascader>
              </el-form-item>
              <el-form-item label="所属部门:" prop="department">
                <el-input v-model="universityForm.department"></el-input>
              </el-form-item>
              <el-form-item label="等级:" prop="level">
                <el-select v-model="universityForm.level">
                  <el-option label="专科" value="专科"></el-option>
                  <el-option label="本科" value="本科"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="简介:" prop="other">
                <el-input
                  type="textarea"
                  v-model="universityForm.other"
                ></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="confirm">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <!-- 展示所有企业 -->
      <el-table :data="university" style="width: 100%; top: 20px">
        <el-table-column fixed prop="schoolName" label="高校名">
        </el-table-column>
        <el-table-column prop="cityInfo.merName" label="所在地">
        </el-table-column>
        <el-table-column prop="level" label="等级"> </el-table-column>
        <el-table-column prop="department" label="直属部门"> </el-table-column>
        <el-table-column prop="schoolId" label="学校代码"> </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button
              @click="handleClick(scope.row.id)"
              type="text"
              icon="el-icon-setting"
              size="small"
              >院系管理</el-button
            >
            <el-button
              @click="edit(scope.row)"
              type="text"
              icon="el-icon-edit"
              size="small"
              >编辑</el-button
            >
            <el-button
              @click="deleteDepartmentById(scope.row.id)"
              type="text"
              style="color: #fa6962"
              icon="el-icon-delete"
              size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
import { provinceAndCityData } from "element-china-area-data"; //引入
import SearchBar from "@/components/OrganizationManagement/SearchBar.vue";
import {
  getUniversity,
  addUniversity,
  updateUniversity,
  searchUniversityByName,
  searchUniversityByCity,
  deleteUniversity,
  exportExcel
} from "#/OrganizationManagement/university.js";
import { addLogs } from "#/Home/Home.js";

export default {
  name: "University",
  meta: {
    title: "高校管理",
  },
  components: {
    SearchBar,
  },
  data() {
    return {
      queryInfo: {
        //查询的内容
        query: "",
        // 当前页数
        pageNum: 1,
        // 每页显示多少数据
        pageSize: 5,
      },
      university: [],
      select: "",
      //总数据条数
      total: 0,
      //添加企业弹窗
      dialogVisible: false,
      updateFlag: false,
      labelPosition: "right",
      universityForm: {
        schoolName: "",
        cityId: "",
        department: "",
        level: "",
        schoolId: "",
        other: "",
      },
      excelImportShow: false,
      fileList: false,
      fileName: "",
      addLoading: false,
      options: provinceAndCityData,
      selectedOptions: [],
      addFlag: true,
    };
  },
  created() {
    this.getUniversities();
  },
  methods: {
    // 所有机构（高校）信息
    async getUniversities() {
      await getUniversity(this.queryInfo.pageNum, this.queryInfo.pageSize).then(
        (res) => {
          const result = res.data;
          console.log(result);
          if (result.ret === 0) {
            this.university = result.orgs.univ.content;
            this.total = result.orgs.univ.totalElements;
          } else {
            this.$message.error("服务器请求错误！");
          }
        }
      );
    },
    confirm() {
      if (this.addFlag) {
        addUniversity(this.universityForm).then((res) => {
          if (res.data.ret == 0) {
            this.$message.success("添加成功");
            this.dialogVisible = false;
            addLogs({
              userId: window.sessionStorage.getItem("userId"),
              behavior: "添加了新的高校信息",
            });
          }
          this.getUniversities();
        });
      } else {
        const id = this.universityForm.id;
        delete this.universityForm.id;
        console.log(this.universityForm);
        updateUniversity(id, this.universityForm).then((res) => {
          if (res.data.ret == 0) {
            this.$message.success("修改成功");
            this.dialogVisible = false;
            addLogs({
              userId: window.sessionStorage.getItem("userId"),
              behavior: "修改了高校信息",
            });
          }
          this.getUniversities();
        });
      }
    },
    edit(obj) {
      this.selectedOptions = [obj.cityInfo.pid + "", obj.cityInfo.id + ""];
      this.addFlag = false;
      Object.assign(this.universityForm, obj);
      delete this.universityForm.cityInfo;
      this.dialogVisible = true;
    },
    //通过高校名模糊搜索高校
    async searchUniversity() {
      if (!this.queryInfo.query) {
        return this.$message.error("请输入名称");
      }
      this.queryInfo.pageNum = 1;
      await searchUniversityByName(this.queryInfo).then((res) => {
        if (res.status === 200) {
          this.university = res.data.orgs.univ.content;
          this.total = res.data.orgs.univ.totalElements;
          if (this.university === []) {
            this.$message.info("搜索结果为空");
          } else {
            this.$message.success("搜索成功！");
          }
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    showAddCom() {
      this.dialogVisible = true;
      this.addFlag = true;
      this.universityForm = {
        schoolName: "",
        cityId: "",
        department: "",
        level: "",
        schoolId: "",
        other: "",
      };
    },
    deleteDepartmentById(id) {
      const confirmResult = this.$confirm(
        "此操作将永久删除该高校, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult === "confirm") {
        deleteUniversity(id).then((res) => {
          console.log(res);
          if (res.data.ret == 0) {
            this.$message.success("删除成功！");
            addLogs({
              userId: window.sessionStorage.getItem("userId"),
              behavior: "成功删除了高校信息信息",
            });
          }
          this.getUniversities();
        });
      }
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getUniversities();
    },
    // 页码改变
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getUniversities();
    },
    handleClick(id) {
      this.$router.push({
        path: `/OrganizationManagement/Department`,
        query: {
          id,
        },
      });
    },
    clearInput() {
      this.queryInfo.pageNum = 1;
      this.queryInfo.pageSize = 5;
      this.getUniversities();
    },
    // 导出Excel表格
    async excelShow() {
      await exportExcel().then(res => {
        if(res.status === 200) {
          const blob = new Blob([res.data], {  // res 为后台返回数据
            type: 'application/vnd.ms-excel;charset=utf-8', // 导出数据生成excel的格式设置
          });
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a');
            elink.download = `高校信息.xlsx`;
            elink.style.display = 'none';
            elink.target = '_blank';
            elink.href = window.URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
          }
        }
      })
    },
    beforeUpload() {},
    handleChange(value) {
      // value = CodeToText(value);
      this.universityForm.cityId = +value[1];
    },
    // 通过地区搜索高校
    async searchSchoolByArea(queryOptions) {
      if (queryOptions.length === 0) {
        this.getUniversities();
      } else {
        await searchUniversityByCity(this.queryInfo, +queryOptions[1]).then(
          (res) => {
            if (res.data.ret === 0) {
              this.university = res.data.orgs.univ.content;
              this.total = res.data.orgs.univ.totalElements;
            }
          }
        );
      }
    },
    excelImport() {},
  },
};
</script>
<style scoped>
.right {
  float: right;
}
</style>
 